package com.tgpms.web.login.controller;

import com.alibaba.fastjson.JSONObject;
import com.tgpms.auth.security.JavaWebToken;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.exception.QueryException;
import com.tgpms.interfaces.Request.HttpClient;
import com.tgpms.interfaces.dto.PortalInterface;
import com.tgpms.interfaces.dto.VformInterface;
import com.tgpms.interfaces.properties.PortalProperties;
import com.tgpms.interfaces.properties.Properties;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.tgpms.auth.security.TokenService;
import com.tgpms.common.Result;
import com.tgpms.util.AESUtil;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Map;

@Api(value = "Login", tags = "Login")
@RestController
@RequestMapping("/")
@Slf4j
public class LoginController {

    @Autowired
    private TokenService tokenService;

    @Resource
    private VformInterface vformInterface;

    @Resource
    private PortalInterface portalInterface;

    @Resource
    private RedisTemplate<String, Object> redis;

    @ApiOperation(value = "Login -> Token", notes = "Login -> Token", httpMethod = "POST")
    @PostMapping(value = "/login")
    public Result testCor(@RequestParam(value = "username", required = false) String username, @RequestParam(value = "password", required = false) String password) {
        Result login = new Result();
        try {
            password = new AESUtil().decryption(password, "12345678");
            login = vformInterface.login(username, password, "");
            if (login.getSuccess()) {
                JSONObject parseObject = (JSONObject) login.getData();
                parseObject.put("token", tokenService.login(username));
                login.setMsg("用户校验通过");
                login.setData(parseObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
            login.setSuccess(false);
        }
        return login;
    }

    /**
     * 通过手机号获取用户信息
     *
     * @param phone
     * @param pp
     * @return Result
     */
    @ApiOperation(value = "通过手机号获取用户信息", notes = "通过手机号获取用户信息", httpMethod = "POST")
    @PostMapping(value = "/getUserTgpmsBymobile")
    public Result getUserTgpmsBymobile(@RequestParam("phone") String phone,
                                       @RequestParam("pp") String pp) {
        Result result = new Result();
        if (StringUtil.isNullOrEmpty(phone)) {
            result.setMsg(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
            result.setSuccess(false);
            throw new QueryException(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
        } else {
            result.setData(vformInterface.getUserTgpmsBymobile(phone, pp));
        }
        return result;
    }

    /**
     * 拿到并解析MyDesk传递过来的Token
     *
     * @param token token
     * @return null
     */
    @ApiOperation(value = "mydesk单点登陆", notes = "mydesk单点登陆", httpMethod = "POST")
    @PostMapping(value = "/parsingMyDeskTokenAndLogin")
    public Result parsingMyDeskTokenAndLogin(@RequestParam("token") String token) {
        Result result = new Result();
        if (StringUtil.isNullOrEmpty(token)) {
            result.setMsg(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
            result.setSuccess(false);
            throw new QueryException(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
        } else {
            Result parseTokenResult = vformInterface.parsingMyDeskToken(token, "", Properties.tns, "");
            String username = "";
            String pwd = "";
            if (parseTokenResult.getSuccess()) {
                cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(parseTokenResult.getData());
                username = jsonObject.getStr("sc_username");
                pwd = jsonObject.getStr("sc_psw");
                String password = this.descrypt(pwd);
                try {
                    Result login = vformInterface.login(username, password, "");
                    if (login.getSuccess()) {
                        cn.hutool.json.JSONObject parseObject = new cn.hutool.json.JSONObject(login.getData());
                        parseObject.put("token", tokenService.login(username));
                        parseObject.put("full_name", jsonObject.getStr("full_name"));
                        parseObject.put("usercode", username);
                        result.setMsg("用户校验通过");
                        result.setData(parseObject);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    result.setSuccess(false);
                }
            }
        }
        return result;
    }

    /**
     * 拿到并解析MyDesk传递过来的Token
     *
     * @param token token
     * @return null
     */
    @ApiOperation(value = "拿到并解析MyDesk传递过来的Token", notes = "拿到并解析MyDesk传递过来的Token", httpMethod = "POST")
    @PostMapping(value = "/parsingMyDeskToken")
    public Result parsingMyDeskToken(@RequestParam("token") String token) {
        Result result = new Result();
        if (StringUtil.isNullOrEmpty(token)) {
            result.setMsg(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
            result.setSuccess(false);
            throw new QueryException(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
        } else {
            result.setData(vformInterface.parsingMyDeskToken(token, "",
                    Properties.tns, ""));
        }
        return result;
    }

    /**
     * 解析MyDesk传递过来的密码
     *
     * @param password 待解密的密码
     * @return null
     */
    @ApiOperation(value = "解析MyDesk传递过来的密码", notes = "解析MyDesk传递过来的密码", httpMethod = "POST")
    @PostMapping(value = "/descrypt")
    public String descrypt(@RequestParam("MDpassword") String password) {
        String parPWD = null;
        try {
            parPWD = vformInterface.descrypt(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return parPWD;
    }

    /**
     * 登出操作
     * 1. 清掉 Cookie ；
     * 2. 清掉 Token
     *
     * @param token token
     * @return null
     */
    @ApiOperation(value = "登出操作", notes = "登出操作", httpMethod = "POST")
    @PostMapping(value = "/logOut")
    public Result logOut(@RequestParam("token") String token) {
        Result result = new Result();
        // 清掉 Cookie
        if (HttpClient.cookiesFull != null) {
            HttpClient.cookiesFull = null;
        }

        // 清掉 Token
        Map<String, Object> map = JavaWebToken.parserJavaWebToken(token);
        if (null == map) {
            result.setMsg(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
            result.setSuccess(false);
            throw new QueryException(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
        }
        try {
            redis.delete(map.get("username").toString());
            redis.delete(map.get("username") + "_Cookie");
        } catch (Exception e) {
            e.printStackTrace();
            throw new QueryException(ExceptionExplain.ERROR_BY_PARSING.getExplain());
        }
        return result;
    }

    /**
     * 通过门户获取token
     *
     * @param code token
     * @return null
     */
    @ApiOperation(value = "通过门户获取token", notes = "通过门户获取token", httpMethod = "POST")
    @PostMapping(value = "/parsingOaToken")
    public Result parsingOaToken(@RequestParam("code") String code) {
        Result result = new Result();
        if (StringUtil.isNullOrEmpty(code)) {
            result.setMsg(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
            result.setSuccess(false);
            throw new QueryException(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
        } else {
            result.setData(portalInterface.parsingOaToken(PortalProperties.clientId, PortalProperties.clientSecret, code, PortalProperties.grantType));
        }
        return result;
    }

    /**
     * 通过门户获取用户信息
     *
     * @param accessToken
     * @param uid
     * @return Result
     */
    @ApiOperation(value = "通过门户获取用户信息", notes = "通过门户获取用户信息", httpMethod = "POST")
    @PostMapping(value = "/parsingGetUserInfo")
    public Result parsingGetUserInfo(@RequestParam("accessToken") String accessToken,
                                     @RequestParam("uid") String uid) {
        Result result = new Result();
        if (StringUtil.isNullOrEmpty(accessToken)) {
            result.setMsg(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
            result.setSuccess(false);
            throw new QueryException(ExceptionExplain.ERROR_BY_TOKEN_EMPTY.getExplain());
        } else {
            result.setData(portalInterface.getUserInfo(accessToken,PortalProperties.clientId,uid));
        }
        return result;
    }
}
